﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;

namespace zielonka.co.uk.extensions.system.drawing
{
    // Description:	This method resizes a System.Drawing.Image and tries to fit it in the destination Size. The source image size may be smaller or bigger then the target size. Source and target layout orientation can be different. ResizeAndFit tries to fit it the best it can.
    /*
        Image image = Image.FromStream(context.Request.InputStream).ResizeAndFit(new Size( 125, 100));
        Image image = Image.FromStream(context.Request.InputStream).ResizeAndFit(125, 100);
     */

    public static partial class ImageExtensions
    {
        public static Image ResizeAndFit(this Image image, Size newSize)
        {
            var sourceIsLandscape = image.Width > image.Height;
            var targetIsLandscape = newSize.Width > newSize.Height;

            var ratioWidth = (double)newSize.Width / (double)image.Width;
            var ratioHeight = (double)newSize.Height / (double)image.Height;

            var ratio = 0.0;

            if (ratioWidth > ratioHeight && sourceIsLandscape == targetIsLandscape)
                ratio = ratioWidth;
            else
                ratio = ratioHeight;

            int targetWidth = (int)(image.Width * ratio);
            int targetHeight = (int)(image.Height * ratio);

            var bitmap = new Bitmap(newSize.Width, newSize.Height);
            var graphics = Graphics.FromImage((Image)bitmap);

            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var offsetX = ((double)(newSize.Width - targetWidth)) / 2;
            var offsetY = ((double)(newSize.Height - targetHeight)) / 2;

            graphics.DrawImage(image, (int)offsetX, (int)offsetY, targetWidth, targetHeight);
            graphics.Dispose();

            return (Image)bitmap;
        }

        public static Image ResizeAndFit(this Image image, int height, int width)
        {
            if (image == null || height <= 0 || width <= 0)
            {
                return null;
            }

            Size newSize = new Size();
            newSize.Width = (image.Width * height) / (image.Height);
            newSize.Height = (image.Height * width) / (image.Width);
            return ResizeAndFit(image, newSize);
        }
    }
}
